﻿using Core.Shop.Model;
using Core.Shop.Model.DTO.BaseInfo;
using Core.Shop.Model.Entity;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using static Core.Shop.Filter.AuthAttribute;

namespace Core.Shop.Api.BaseInfo
{
    public class MenuController : BaseController
    {
        //[NoPermissionRequired]
        [HttpGet]
        public object Get()
        {
            var menus = Db.Menu.ToList();
            var menuDTOs = new List<MenuDTO>();
            menuDTOs = GetMenuTree(menuDTOs, menus);
            return ReturnModel.Success(menuDTOs);
        }

        private List<MenuDTO> GetMenuTree(List<MenuDTO> menus,List<Menu> allMenus)
        {
            if (menus.Count == 0)
            {
                menus = allMenus.Where(m => m.ParentId == 0).Select(m => new MenuDTO()
                {
                    Icon = m.Icon,
                    Id = m.Id,
                    Name = m.Name,
                    Url = m.Url,
                    Sort = m.Sort,
                }).OrderBy(m => m.Sort).ToList();
                GetMenuTree(menus, allMenus);
            }
            else
            {
                foreach (var menu in menus)
                {
                    menu.ChlidMenus = allMenus.Where(m => m.ParentId == menu.Id).Select(m => new MenuDTO()
                    {
                        Id = m.Id,
                        Name = m.Name,
                        Url = m.Url,
                        Icon = m.Icon,
                        Sort = m.Sort
                    }).ToList();
                    if (menu.ChlidMenus.Count == 0) return menus;
                    GetMenuTree(menu.ChlidMenus, allMenus);
                }
            }
            return menus;
        }
    }
}
